function plot_dens(xmat,dist,alphap,betap,into,cofname,opath,append);
% ======================================================================
% PLOT_DENS 
%
% Given a set of draws in xmat [t n ch] 
% Compute 1) Normal Kernel estimates 
%         2) Shaded bar plots
% Plot each of them, one at a time, for all coefficients, in pages of into.r into,c 
% dimension each. 
% Output plots will be called post_nkdens<i> post_hist<i> indexed as needed 
% 
% Inputs 
% =======
% xmat      [t,n,p] 
% dist,alphap and betap control the prior 
%           and must be used after scaling them by indp 
%           to remove the calibrated coefficients 
% cofname   (optional) coefficient names 
%           (leave [] or do not call if do not wish to provide any)
% opath     path where to save files
%           ( leave [] or do not call if do not wish to provide any) 
% append    string to append to the names of the figures 
% 
% into             Structure 
% into.addt        String to add to title 
%                  Title will be [cofnam into.addt]
% into.tfsize      Title Font Size 
% into.lfsize      Legend Font Size 
% into.nbins       Number of bins for the hist plots 
% into.r           Row dimension of suplots 
% into.c           Column dimension of suplots
% into.ylim        Vector/Matrix of Ylims 
%                  Can be 1x2 or [c x 2] with a limit for each column 
%                  If both entries are equal then ylim is automatic 
%                  over the range of prior and posterior 
% 
%
% Copyright (C) Alejandro Justiniano 
%
% 11/25/2005 
% ================================================================= 
legcell={'Posterior','Prior'};  %Legend cell
cucd=cd;
if nargin < 7 | isempty( opath ); 
    saveflag = 0 ;
else
    saveflag = 1 ;
    if nargin == 7
        append = [];
    else
        append=char(append) ;
    end
end

if nargin <4
    error('Need dist, alphap and betap for the prior' )
end
    
if saveflag==1; 
    cd(opath); 
    cd(cucd); 
end 
[t,n,p]=size(xmat);
t=t*p; 

if t < 500; 
    error('Need more than 500 draws per series'); 
end; 

if nargin < 6 | isempty(cofname) == 1 ; 
    cofname=fnumcell('cof ',[1:n]); 
else
    cofname=cofname(:); 
    if size(cofname,1)~=n; error('coefname dimension mistmatch draws'); end; 
end 

% ===================
% Check dimensions 
% ====================
if t < n; warning('Number of series exceed the draws per series'); end;

dist=dist(:); 
dist=char(dist); 
if size(dist,1)~=n;error('dist dimension mistmatch draws'); end; 
if size(alphap,1)~=n;error('alphap dimension mistmatch draws'); end; 
if size(betap,1)~=n;error('betap dimension mistmatch draws'); end; 
if iscell(dist) == 1
    dist=char(dist);
end

disp('Individual plots for coefficients diagnostics'); 


set(0,'DefaultAxesFontSize',7); 
[e,into]=ch_field(into,'r', 3 ); 
[e,into]=ch_field(into,'c', 3 ); 
[e,into]=ch_field(into,'addt',' '); 
[e,into]=ch_field(into,'ylim');
[e,into]=ch_field(into,'tfsize',9); 
[e,into]=ch_field(into,'lfsize',7); 
[e,into]=ch_field(into,'nbins',25); 

if e==1; 
    if size( into.ylim , 2 ) ~= 2 
        error('Column dimension of ylim must be 2'); 
    end 
    if size( into.ylim , 1) == 1 
        into.ylim = repmat( into.ylim , [n,1] ); 
    elseif size( into.ylim,1  ) ~= n 
        error('INTO.YLIM must either be a scalar or match number of coefficient columns') 
    end 
    flag_ylim = 1; 
else
    flag_ylim = 0;    
end 

% ============================================================
%     Compute the Normal Kernel and Epanechnikov Kernel      %
%             For prior and posterior                        %
% ===========================================================


prdraws = zeros( t , n ); 
ylimat  = zeros( n , 2 ); 

% =========================
% Loop over what to plot 
% =======================
np = 100; 

aa=1; 
for aa =1:2; 
    
    if aa==1
        disp('________________________________________');
        disp('Normal Kernel Plots');
    else
        disp('________________________________________');
        disp('Histograms');
    end

        
    gind = 0;
    numg = 0; %Number of Graph 
    cind = 0; %Counter 
    
    jj=1;
    for jj=1:n;

        cname=cofname{jj};
        disp(['Diagnostics for coefficient: ',cname]);
        x=xmat(:,jj,:);
        x=x(:);
        
        if gind == 0
            figure;
            gind = 1; 
        end

        numg = numg + 1;      
        % ======================
        % Normal Kernel Plots
        % ======================
        switch aa

            case 1
                % ========================================
                % Set the limits for the plots, if needed
                % Generate prior draws
                % Plot Normal Kernels
                % =========================================
                rootstr ='NK';  
                plot_dens_kern;
            case 2
                subplot( into.r , into.c , numg ); 
                rootstr ='Bar';  
                binedge=linspace( ylimat(jj,1) , ylimat(jj,2) , into.nbins  ); 
                [N1,BIN1]=histc(x,binedge);
                N1=N1/t;
                [N2,BIN2]=histc(prdraws,binedge);
                N2=N2/t;
                bar(binedge,[N1 N2] , 1.4 )
                r1=[0 0 0];
                r2=[100/255 1 220/255];
                r=[r1;r2];
                colormap(r);
                if numg == 1
                    lhand=legend('Po','Pr',0);
                    set(lhand,'FontSize',into.lfsize,'FontWeight','Bold','FontAngle','italic');
                end
                clear N1 BIN1 B2 BIN2 r1 r2 r;
                axis tight;
                title([cname] , 'FontSize',into.tfsize,'FontWeight','Bold','FontAngle','italic');
                clear binedge;

        end

        if numg == into.r*into.c |  jj==n

            gind = 0;
            numg = 0;
            cind = cind + 1;

            if saveflag == 1;
                temp=[roostr,' ',num2str( cind ) ];
                cd(opath);
                saveas(gcf,temp,'fig');
                disp(['Saved Graph ,',temp]);
                cd(cucd);
            end;
            
        end 
        
    end % END jj 
    
end % END aa 